const express = require('express');
const fm = require('formidable');
let path = require('path');
const jwt = require('jsonwebtoken');
const md5 = require('md5');
const db = require('../db/index.js');
const { getSecret } = require('../utils/index.js');

const config = getSecret();

const secretKey = config.jwtSecret;

const router = express.Router();

// token登录
router.post('/login', async (req, res, next) => {
  const { username, password } = req.body;
  // 验证用户名和密码是否为空
  if (!username || !password) {
    return res.status(400).json({ error: '账号和密码必填' });
  }
  try {
    // 查询用户是否存在以及密码是否匹配
    const sql = 'SELECT * FROM users WHERE username =? AND password =?';

    const [users] = await db.execute(sql, [username, md5(password)]);

    if (users.length === 1) {
      // 登录成功，可在这里生成并返回一个token（用于后续的认证），这里简单返回用户信息
      const token = jwt.sign(
        {
          username,
        },
        secretKey,
        {
          expiresIn: 60 * 60 * 24 * 7,
        },
      );

      res.status(200).json({
        code: 0,
        message: '登录成功了~',
        data: token,
      });
    } else {
      res.status(200).json({ code: -1, error: '用户名或密码不正确' });
    }
  } catch (error) {
    res.status(500).json({ error: '网络错误' });
  }
});

module.exports = router;
